#!/usr/bin/env bash

# Exit build script on first failure.
set -e

# Echo commands.
set -x

if [[ -z $1 ]]; then
  MODE='prod'
else
  MODE="$1"
fi

PLATFORM="${TARGETPLATFORM:-linux/amd64}"

# Exit on unset variable.
set -u

GO_BUILD_TAGS=()
BINARY='./bin/logpaste'

GO_BUILD_TAGS+=('netgo')
# Disable dynamically-loaded extensions, which cause a compile time warning.
# https://www.arp242.net/static-go.html
GO_BUILD_TAGS+=('sqlite_omit_load_extension')

if [[ "${MODE}" != 'prod' ]]; then
  BINARY="${BINARY}-${MODE}"
  GO_BUILD_TAGS+=("${MODE}")
fi
readonly BINARY
readonly GO_BUILD_TAGS

readonly GOOS='linux'
export GOOS
if [ "${PLATFORM}" = 'linux/amd64' ]; then
  GOARCH='amd64'
elif [ "${PLATFORM}" = 'linux/arm/v7' ]; then
  GOARCH='arm'
elif [ "${PLATFORM}" = 'linux/arm64' ]; then
  GOARCH='arm64'
else
  echo "Unsupported platform: ${PLATFORM}"
  exit 1
fi
readonly GOARCH
export GOARCH

# Join together build tags
BUILD_TAGS_JOINED=""
for tag in "${GO_BUILD_TAGS[@]}"; do
    BUILD_TAGS_JOINED+=" $tag"
done

# Trim leading space.
BUILD_TAGS_JOINED="${BUILD_TAGS_JOINED# }"
readonly BUILD_TAGS_JOINED

# cgo is required for mattn/go-sqlite3.
export CGO_ENABLED=1

go build \
  -tags "${BUILD_TAGS_JOINED}" \
  -ldflags '-w -extldflags "-static"' \
  -o "${BINARY}" \
  cmd/logpaste/main.go
